<script lang="ts" setup>
import { reactive, ref, watch } from "vue"
import { getVipUserDataApi, deleteVipUserDataApi, updateVipUserDataApi } from "@/api/vipUser"
import { type CreateOrUpdateVipUserRequestData, type GetVipUserData } from "@/api/vipUser/types/vipUser"
import { type FormInstance, type TableColumnCtx, ElMessage, ElMessageBox } from "element-plus"
import { Search, Refresh, Delete, RefreshRight } from "@element-plus/icons-vue"
import { usePagination } from "@/hooks/usePagination"
import { cloneDeep } from "lodash-es"
import { getToken } from "@/utils/cache/cookies"
defineOptions({
  // 命名当前组件
  name: "ElementPlus"
})

const uploadHeaders = ref<any>("")
uploadHeaders.value = getToken()
const loading = ref<boolean>(false)
const { paginationData, handleCurrentChange, handleSizeChange } = usePagination()

//#region 增
const DEFAULT_FORM_DATA: CreateOrUpdateVipUserRequestData = {
  id: "",
  status: 1,
  remake: ""
}
// const checkPhone = (rule: any, value: any, callback: any) => {
//   if (!value) {
//     return callback(new Error("请输入手机号"))
//   }
//   setTimeout(() => {
//     console.log(!isPhoneNumber(value))
//     if (!isPhoneNumber(value)) {
//       return callback(new Error("请输入正确的手机号"))
//     } else {
//       callback()
//     }
//   }, 1000)
// }
const dialogVisible = ref<boolean>(false)
const formRef = ref<FormInstance | null>(null)
const formData = ref<CreateOrUpdateVipUserRequestData>(cloneDeep(DEFAULT_FORM_DATA))
// const formRules: FormRules<CreateOrUpdateVipUserRequestData> = {
//   userName: [{ required: true, trigger: "blur", message: "请输入用户名" }],
//   password: [
//     { required: true, trigger: "blur", message: "请输入密码" },
//     { min: 6, max: 12, message: "密码长度在6到12位之间", trigger: "blur" }
//   ],
//   name: [{ required: true, trigger: "blur", message: "请输入昵称" }],
//   phone: [{ required: true, trigger: "blur", validator: checkPhone }]
//   // age: [{ required: true, trigger: "blur", message: "请输入年龄" }]
// }
const handleCreateOrUpdate = () => {
  formRef.value?.validate((valid: boolean, fields) => {
    if (!valid) return console.error("表单校验不通过", fields)
    loading.value = true
    updateVipUserDataApi(formData.value)
      .then(() => {
        ElMessage.success("操作成功")
        dialogVisible.value = false
        getTableData()
      })
      .finally(() => {
        loading.value = false
      })
  })
}
const resetForm = () => {
  formRef.value?.clearValidate()
  formData.value = cloneDeep(DEFAULT_FORM_DATA)
}
//#endregion

//#region 删
const handleDelete = (row: GetVipUserData) => {
  ElMessageBox.confirm(`正在删除用户：${row.name}的会员申请，确认删除？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    deleteVipUserDataApi(row.id).then(() => {
      ElMessage.success("删除成功")
      getTableData()
    })
  })
}
const getSelectionList = ref([])
const selectionList = (e: any) => {
  getSelectionList.value = e
}
const deleteAll = () => {
  ElMessageBox.confirm(`正在删除所有记录，确认删除？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    const list: any[] = []
    getSelectionList.value.forEach((res: any) => {
      list.push(res.id)
    })
    deleteVipUserDataApi(list.join(",")).then(() => {
      ElMessage.success("删除成功")
      getTableData()
    })
  })
}
//#endregion

//#region 改
const handleUpdate = (row: GetVipUserData) => {
  dialogVisible.value = true
  formData.value.id = row.id
}
//#endregion

//#region 查
const tableData = ref<GetVipUserData[]>([])
const searchFormRef = ref<FormInstance | null>(null)
const searchData = reactive({
  userName: ""
})
const getTableData = () => {
  loading.value = true
  getVipUserDataApi({
    pageNum: paginationData.currentPage,
    pageSize: paginationData.pageSize,
    userName: searchData.userName
  })
    .then(({ data }) => {
      paginationData.total = data.total
      tableData.value = data.rows
    })
    .catch(() => {
      tableData.value = []
    })
    .finally(() => {
      loading.value = false
    })
}
const handleSearch = () => {
  paginationData.currentPage === 1 ? getTableData() : (paginationData.currentPage = 1)
}
const resetSearch = () => {
  searchFormRef.value?.resetFields()
  handleSearch()
}
//#endregion

/** 监听分页参数的变化 */
watch([() => paginationData.currentPage, () => paginationData.pageSize], getTableData, { immediate: true })

const formatter = (row: GetVipUserData, column: TableColumnCtx<GetVipUserData>) => {
  let ret = ""
  if (column.property == "type") {
    const type = row.type
    switch (type) {
      case 1:
        ret = "月卡"
        break
      case 2:
        ret = "季卡"
        break
      default:
        ret = "年卡"
        break
    }
  } else if (column.property == "status") {
    const type = row.type
    switch (type) {
      case 0:
        ret = "待审核"
        break
      case 1:
        ret = "通过"
        break
      default:
        ret = "驳回"
        break
    }
  }
  return ret
}
</script>

<template>
  <div class="app-container">
    <el-card v-loading="loading" shadow="never" class="search-wrapper">
      <el-form ref="searchFormRef" :inline="true" :model="searchData">
        <el-form-item prop="username" label="用户名">
          <el-input v-model="searchData.userName" placeholder="请输入" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
          <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card v-loading="loading" shadow="never">
      <div class="toolbar-wrapper">
        <div>
          <el-button type="danger" :icon="Delete" @click="deleteAll">批量删除</el-button>
        </div>
        <div>
          <el-tooltip content="刷新当前页">
            <el-button type="primary" :icon="RefreshRight" circle @click="getTableData" />
          </el-tooltip>
        </div>
      </div>
      <div class="table-wrapper">
        <el-table :data="tableData" @selection-change="selectionList">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column prop="avatar" label="头像" align="center">
            <template #default="scope">
              <el-avatar :size="50" :src="scope.row.avatar" />
            </template>
          </el-table-column>
          <el-table-column prop="userName" label="用户名" align="center" />
          <el-table-column prop="name" label="昵称" align="center" />
          <el-table-column prop="status" label="状态" align="center" :formatter="formatter" />
          <el-table-column prop="type" label="申请类型" align="center" :formatter="formatter" />
          <el-table-column prop="createTime" label="创建时间" align="center" />
          <el-table-column fixed="right" label="操作" width="150" align="center">
            <template #default="scope">
              <el-button
                v-if="scope.row.status == 0"
                type="primary"
                text
                bg
                size="small"
                @click="handleUpdate(scope.row)"
                >审批</el-button
              >
              <el-button v-else text bg size="small">已审批</el-button>
              <el-button type="danger" text bg size="small" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pager-wrapper">
        <el-pagination
          background
          :layout="paginationData.layout"
          :page-sizes="paginationData.pageSizes"
          :total="paginationData.total"
          :page-size="paginationData.pageSize"
          :currentPage="paginationData.currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    <!-- 新增/修改 -->
    <el-dialog v-model="dialogVisible" title="审核" @closed="resetForm" width="30%">
      <el-form ref="formRef" :model="formData" label-width="100px" label-position="left">
        <el-form-item prop="status" label="审核">
          <el-radio-group v-model="formData.status" class="ml-4">
            <el-radio :value="1" size="large">通过</el-radio>
            <el-radio :value="2" size="large">驳回</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item prop="remake" label="驳回原因">
          <el-input v-model="formData.remake" placeholder="请输入" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleCreateOrUpdate" :loading="loading">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.search-wrapper {
  margin-bottom: 20px;
  :deep(.el-card__body) {
    padding-bottom: 2px;
  }
}

.toolbar-wrapper {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.table-wrapper {
  margin-bottom: 20px;
}

.pager-wrapper {
  display: flex;
  justify-content: flex-end;
}
</style>
